package me.xiaoyan.android.widget;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.xiaoyan.android.net.AsyncHttpGet;
import me.xiaoyan.android.net.RequestListener;
import me.xiaoyan.android.net.WebParameters;
import me.xiaoyan.android.net.HttpManager.HTTPMETHOD;
import me.xiaoyan.android.widget.AuthCode;
import me.xiaoyan.android.widget.CardStorageManager;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

/**
 * 基础工具类
 * 
 * @author xiaoyan
 * 
 */
public class BaseUtil {
	private static final String TAG = "BASEUtil";

	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static float dip2pxf(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return dipValue * scale + 0.5f;
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static String getIMEI(Context context) {
		return ((TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
	}

	public static String getApplicationVersion(Context context)
			throws NameNotFoundException {

		PackageManager packageManager = context.getPackageManager();
		PackageInfo packInfo = packageManager.getPackageInfo(
				context.getPackageName(), 0);
		return packInfo.versionName;
	}

	public static int getPhoneWidthDip(Activity activity) {
		return px2dip(activity, getPhoneWidthPixle(activity));
	}

	public static int getPhoneWidthPixle(Activity activity) {
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		return dm.widthPixels;
	}
	
	public static boolean isPhoneNumber(String phoneNumber){
		Pattern p = Pattern.compile("^[1][358]\\d{9}$");
		Matcher m = p.matcher(phoneNumber);
		return m.matches();
	}

	public static int getPhoneHeightPixle(Activity activity) {
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		return dm.heightPixels;
	}

	public static boolean stringIsEmpty(String str) {
		return null == str ? true : ("".equals(str) ? true : false);
	}

	/**
	 * 获取数据
	 * 
	 * @param handler
	 * @param params
	 */
	public static void AsyncGetHttpData(
			final DataBackListener dataBackListener, WebParameters params,
			HTTPMETHOD method) {
		final Handler handler = StaticData.getInstance().getHandler();

		AsyncHttpGet.request(AppSetting.BASE_API, params, method,
				new RequestListener() {
					@Override
					public void onError(Exception e) {
						Message msg = handler.obtainMessage(-1,
								dataBackListener);
						Bundle data = new Bundle();
						data.putString("source", e.getMessage());
						msg.setData(data);
						handler.sendMessage(msg);
					}

					@Override
					public void onComplete(Object resp) {
						Message msg = handler
								.obtainMessage(0, dataBackListener);
						Bundle data = new Bundle();
						data.putString("source", new String((byte[]) resp));
						msg.setData(data);
						handler.sendMessage(msg);
					}
				});
	}

	/**
	 * 获取数据
	 * 
	 * @param handler
	 * @param params
	 */
	public static void AsyncGetHttpData(
			final DataBackListener dataBackListener, String params,
			HTTPMETHOD method) {
		final Handler handler = StaticData.getInstance().getHandler();

		AsyncHttpGet.request(AppSetting.BASE_API, params, method,
				new RequestListener() {
					@Override
					public void onError(Exception e) {
						Message msg = handler.obtainMessage(-1,
								dataBackListener);
						Bundle data = new Bundle();
						data.putString("source", e.getMessage());
						msg.setData(data);
						handler.sendMessage(msg);
					}

					@Override
					public void onComplete(Object resp) {
						Message msg = handler
								.obtainMessage(0, dataBackListener);
						Bundle data = new Bundle();
						data.putString("source", new String((byte[]) resp));
						msg.setData(data);
						handler.sendMessage(msg);
					}
				});
	}

	public static Long getTimestamp() {
		String time = "" + System.currentTimeMillis();
		return Long.parseLong(time.substring(0, 10));
	}

	public static boolean saveCache(Class<?> cls, String source) {
		return saveCache(cls, source, "");
	}

	public static String getCache(Class<?> cls) {
		return getCache(cls, "");
	}

	public static boolean saveCache(Class<?> cls, String source, String tag) {
		String fileName = getCacheFileName(cls, tag);
		return CardStorageManager.getInstance().saveString(source, fileName);
	}

	public static String getCache(Class<?> cls, String tag) {
		String fileName = getCacheFileName(cls, tag);
		File cachefile = new File(fileName);
		if (!cachefile.exists()) {
			return null;
		}
		return CardStorageManager.getInstance().readString(fileName);
	}

	private static String getCacheFileName(Class<?> cls, String tag) {
		String md5 = AuthCode.getInstance().base64_encode(cls.getName() + tag);
		if (AppSetting.HAS_SDCARD) {
			File dir = new File(AppSetting.APP_CACHE_SOURCE);
			if (!dir.exists()) {
				dir.mkdirs();
			}
		}
		return AppSetting.APP_CACHE_DIR + md5 + ".source";
	}

	public static Bitmap getImageCache(String url) {
		String filename = getCachePcitureFileName(url);
		if(null == filename){return null;}
		File file = new File(filename);
		if (file.exists()) {
			return BitmapFactory.decodeFile(filename);
		}
		return null;
	}

	public static Bitmap zoomImage(float width, float height, Bitmap bitmap) {
		int orgwidth = bitmap.getWidth();
		int orgheight = bitmap.getHeight();
		float scaleWidth = width / orgwidth;
		float scaleHeight = height / orgheight;
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);

		return Bitmap.createBitmap(bitmap, 0, 0, orgwidth, orgheight, matrix,
				true);
	}

	public static Bitmap zoomImage(float width, Bitmap bitmap) {
		int orgwidth = bitmap.getWidth();
		int orgheight = bitmap.getHeight();
		float scale = width / orgwidth;
		float height = orgheight * scale; // 获取缩放高度

		return zoomImage(width, height, bitmap);
	}

	public static void saveImageCache(String url, Bitmap bitmap) {
		if (null != bitmap) {
			String filename = getCachePcitureFileName(url);
			if(filename != null){
				try {
					FileOutputStream out = new FileOutputStream(filename);
					url = url.toLowerCase(Locale.getDefault());
					if (url.indexOf(".png") > -1) {
						bitmap.compress(CompressFormat.PNG, 100, out);
					} else {
						bitmap.compress(CompressFormat.JPEG, 100, out);
					}
				} catch (FileNotFoundException e) {
					YLog.e(TAG, "FileNotFoundException(105)", e.toString());
				}
			}
			
		}
	}

	private static String getCachePcitureFileName(String url) {
		String md5 = AuthCode.getInstance().md5(url);
		String imageDir = AppSetting.APP_IMAGE_DIR + md5.substring(0, 2) + "/";
		if (AppSetting.HAS_SDCARD) {
			File dir = new File(imageDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
		}else{
			return null;
		}

		String prefix = url.toLowerCase(Locale.CHINESE).endsWith(".png") ? ".png"
				: ".jpg";
		return imageDir + md5 + prefix;
	}
}
